<!-- 商户列表 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" @changeSize="changeSize" :showExport="true" @download="getSearchList('export')"
    @changePage="changePage" @search="getSearchList" @changeTh="data.dialogVisible = true" @reset="onHideDetails(true)">
    <template #form>
      <Operator ref="OperatorRef" @query="queryItem" />
      <el-form-item label="商户类型" v-if="!indexStore.is_general_agent">
        <el-select v-model="data.query.agent_type" placeholder="请选择">
          <el-option v-for="item in data.typeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select class="selectWidth120" v-model="data.query.type" placeholder="请选择">
          <el-option v-for="item in data.conditionList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input class="width200" type="number" v-model="data.query.app_id" placeholder="请输入" onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
      <el-form-item label="商户名称：">
        <el-input v-model="data.query.agent_name" placeholder="请输入商户名称" onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
      <el-form-item label="账号：">
        <el-input v-model="data.query.account" placeholder="请输入账号" onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
    </template>
    <template #button>
      <div class="statistic flex">
        <el-button icon="Plus" type="primary" @click="changeMerchant({},'change')">创建商户</el-button>
        <el-button class="marginR20" type="danger"
          @click="getCommercialList(-1), data.isShowApi = true">API控制</el-button>
        <div class="flex" v-if="!indexStore.is_general_agent">
          <el-select class="selectWidth120 marginR20" v-model="data.querySum.type" placeholder="日期请选择"
            @change="chooseDate">
            <el-option v-for="item in data.totalDate" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-tooltip effect="light" placement="bottom">
            <template #content>
              <div class="flexWrap" v-if="data.totalForm.total_operator.length">
                <div class="margin5" v-for="item in data.totalForm.total_operator" :key="item">
                  【{{ item }}】{{ selectToLabel(indexStore.operatorArray, item) }}
                </div>
              </div>
              <span v-else>暂无数据</span>
            </template>
            <p>总代数量：<span class="colorRed details">{{
              data.totalForm.total_operator ? data.totalForm.total_operator.length:0 }}</span>
            </p>
          </el-tooltip>
          <el-tooltip effect="light" placement="bottom">
            <template #content>
              <div class="flexWrap" v-if="data.totalForm.agent_num.length">
                <div class="margin5" v-for="item in data.totalForm.agent_num" :key="item">
                  【{{ item }}】{{ selectToLabel(indexStore.agentArray, item) }}
                </div>
              </div>
              <span v-else>暂无数据</span>
            </template>
            <p>商户数量：<span class="colorRed details">{{ data.totalForm.agent_num ? data.totalForm.agent_num.length : 0
                }}</span></p>
          </el-tooltip>
          <el-tooltip effect="light" placement="bottom">
            <template #content>
              <div class="flexWrap" v-if="data.totalForm.access_agent_num.length">
                <div class="margin5" v-for="item in data.totalForm.access_agent_num" :key="item">
                  【{{ item }}】{{ selectToLabel(indexStore.agentArray, item) }}
                </div>
              </div>
              <span v-else>暂无数据</span>
            </template>
            <p>正在接入的商户数量：<span class="colorRed details">{{
              data.totalForm.access_agent_num ? data.totalForm.access_agent_num.length:0 }}</span></p>
          </el-tooltip>
          <el-tooltip effect="light" placement="bottom">
            <template #content>
              <div class="flexWrap" v-if="data.totalForm.line_agent_num.length">
                <div class="margin5" v-for="item in data.totalForm.line_agent_num" :key="item">
                  【{{ item }}】{{ selectToLabel(indexStore.agentArray, item) }}
                </div>
              </div>
              <span v-else>暂无数据</span>
            </template>
            <p>已经上线的商户数量：<span class="colorRed details">{{ data.totalForm.line_agent_num ? data.totalForm.line_agent_num.length:0 }}</span></p>
          </el-tooltip>
        </div>
      </div>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
          show-overflow-tooltip>
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content> {{ item.tips }} </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'operated_id'" #default="scope">
            <div class="flex">
              <div style="width: 70px;">
                <el-tag v-if="!indexStore.is_general_agent" size="small" :type="scope.row.operated_id == 1 ? 'success' : scope.row.is_multi_currency ? 'danger' : 'warning'"
                  style="font-size:10px;">
                  {{ scope.row.operated_id == 1 ? '直营' : scope.row.is_multi_currency ? '多货币展开' : '正常总代' }}
                </el-tag>
              </div>
              <span :class="scope.row.is_multi_currency ? 'item_details' : ''"
                @click="getSunList(scope.row)">
                {{ selectToLabel(indexStore.operatorArray, scope.row.operated_id) }}
                <span class="tipsTextRed" v-if="scope.row.is_multi_currency ? true : false">({{
                scope.row?.son_data?.length }})</span>
              </span>
            </div>
          </template>
          <template v-if="item.prop == 'area'" #default="scope">
            {{ selectToLabel(COUNTRY, scope.row.area) }}
          </template>
          <template v-if="item.prop == 'pre_store_score'" #default="scope">
            <div v-if="scope.row.pre_score_status">
              <span :class="colorClass(scope.row.agent_month_game_income)">{{ BigDiv(BigWan(scope.row.agent_month_game_income),scope.row.settlement_ratio) }}</span>/{{ scope.row.agent_grade }}
            </div>
            <div v-else> - </div>
          </template>
          <template v-if="item.prop == 'threshold'" #default="scope">
            <div v-if="scope.row.pre_score_status" class="flexBetween">
              <el-button class="button_icon" icon="Edit" type="warning" size="small" @click="changeMerchant(scope.row,'score')"/>
              <!-- 阈值 = 预存分*(1+比例) -->
              <div class="width80 textCenter">{{ BigTimes(scope.row.agent_grade,BigHundred(scope.row.pre_score_percent)+1) }}</div>
            </div>
            <div v-else> - </div>
          </template>
          <template v-if="item.prop == 'agent_type'" #default="scope">
            <el-tag :type="scope.row.agent_type ? 'danger' : 'success'">
              {{ scope.row.agent_type ? '测试商户' : '正常商户' }}{{ scope.row.kol?' - KOL':'' }} 
            </el-tag>
          </template>
          <template v-if="item.prop == 'config_ggr'" #default="scope">
            <span class="marginR5" v-for="(second,two) in scope.row.config_ggr">
              {{ selectToLabel(GameBrandNum, second.platform)}}:{{second.radio}}%
            </span>
          </template>
          <template v-if="item.prop == 'api_type'" #default="scope">
            {{ selectToLabel(APITYPE, scope.row.api_type) }}
          </template>
          <template v-if="item.prop == 'currency_id'" #default="scope">
            {{ AgentCurrency(scope.row.id) }}
          </template>
          <template v-if="item.prop == 'created_at'" #default="scope">
            {{ setTimestampTime(scope.row.created_at) }}
          </template>
          <template v-if="item.prop == 'last_login_time'" #default="scope">
            {{ setTimestampTime(scope.row.last_login_time) }}
          </template>
          <template v-if="item.prop == 'client_lang'" #default="scope">
            {{ LangConversion(indexStore.langList, scope.row.client_lang) }}
          </template>
          <template v-if="item.prop == 'status'" #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">{{
              selectToLabel(DEMOPLAY, scope.row.status)
            }}</el-tag>
          </template>
          <template v-if="item.prop == 'slot_ratio'" #default="scope">
            {{ scope.row.slot_ratio }}%
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="320">
        <template #header>
          <el-tooltip effect="dark" placement="top">
            <template #content>
              模拟登陆：点击可直接登录商户的后台，无需账号密码输入；<br />
              关闭/开启API：控制商户的API接口；关闭后商户玩家无法进入游戏；<br />
              编辑：编辑商户的信息设定及后台账号等；<br />
              删除：删除商户，数据与接口一并删除；此操作无法恢复，谨用；<br />
            </template>
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <div class="flex">
            <el-button :type="scope.row.is_multi_currency ? 'info' : 'primary'" v-permiss="'/system/changeManager'"
              size="small" :disabled="scope.row.is_multi_currency ? true : false" @click="agentLogin(scope.row)">
              模拟登录
            </el-button>
            <el-button :disabled="(scope.row.is_multi_currency != 1 && scope.row.operator_status) ? false : true"
              :type="scope.row.status ? 'info' : 'success'" v-permiss="'/system/changeManager'" size="small"
              @click="beforeChange(scope.row)">
              {{ scope.row.status ? '关闭API' : '开启API' }}
            </el-button>
            <el-button :disabled="scope.row.is_multi_currency ? true : false" type="warning"
              v-permiss="'/system/changeManager'" size="small" @click="changeMerchant(scope.row,'change')">
              编辑
            </el-button>
            <el-button type="danger" v-permiss="'/system/destroyManager'" size="small" @click="deleteMerchant(scope.row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 新增  编辑  -->
  <PageDetails :show="data.formDialogShow" :checkedItem="data.checkedItem" @cancel="cancel" />

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"></tableHeader>

  <!-- 下级商户 -->
  <el-dialog v-model="data.isShowDetails" title="下级商户" width="80%" :close-on-click-modal="false"
    :close-on-press-escape="false" top="12vh" @close="onHideDetails" class="dialogMaxHeight">
    <template #header>
      <p class="box-title" style="color:crimson">
        【{{ data.checkedItem.operated_id }}】 {{ selectToLabel(indexStore.operatorArray, data.checkedItem.operated_id) }}
      </p>
    </template>
    <SearchTable :query="data.query" :list="data.listDetails" :total="0" :showSet="false" :showForm="false">
      <template #form> </template>
      <template #button></template>
      <template #table>
        <el-table-column type="index" width="70" label="序号" />
        <template v-for="(item, index) in data.fields" :key="index">
          <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
            show-overflow-tooltip>
            <template #header>
              <el-tooltip v-if="item.tips" effect="dark" placement="top">
                <template #content> {{ item.tips }} </template>
                <el-icon class="ques-tips">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              {{ item.label }}
            </template>
            <template v-if="item.prop == 'operated_id'" #default="scope">
              <div class="flex">
                <div style="width: 70px;">
                  <el-tag v-if="!indexStore.is_general_agent" size="small"
                    :type="selectToLabel(indexStore.operatorArray, scope.row.operated_id, 'currency', 'value') == 1 ? 'danger' : 'warning'"
                    style="font-size:10px;">
                    {{ selectToLabel(indexStore.operatorArray, scope.row.operated_id, 'currency', 'value') == 1 ? '多货币展开' :
                      '正常总代' }}
                  </el-tag>
                </div>
                <span>{{ selectToLabel(indexStore.operatorArray, scope.row.operated_id) }}</span>
              </div>
            </template>
            <template v-if="item.prop == 'area'" #default="scope">
              {{ selectToLabel(COUNTRY, scope.row.area) }}
            </template>
            <template v-if="item.prop == 'agent_type'" #default="scope">
              <el-tag :type="scope.row.agent_type ? 'danger' : 'success'">
                {{ scope.row.agent_type ? '测试商户' : '正常商户' }}
              </el-tag>
            </template>
            <!-- <template v-if="item.prop == 'game'" #default="scope">
              <span class="marginR5" v-for="(second, two) in scope.row.gameList" :key="two">
                {{ selectToLabel(indexStore.gameArray, second) }}
                <span
                  v-if="two != scope.row.gameList?.length - 1 && selectToLabel(indexStore.gameArray, second)">,</span>
              </span>
            </template> -->
            <template v-if="item.prop == 'api_type'" #default="scope">
              {{ selectToLabel(APITYPE, scope.row.api_type) }}
            </template>
            <template v-if="item.prop == 'created_at'" #default="scope">
              {{ setTimestampTime(scope.row.created_at) }}
            </template>
            <template v-if="item.prop == 'last_login_time'" #default="scope">
              {{ setTimestampTime(scope.row.last_login_time) }}
            </template>
            <template v-if="item.prop == 'client_lang'" #default="scope">
              {{ LangConversion(indexStore.langList, scope.row.client_lang) }}
            </template>
            <template v-if="item.prop == 'status'" #default="scope">
              <el-tag :type="scope.row.status ? 'success' : 'danger'">{{
                selectToLabel(DEMOPLAY, scope.row.status)
              }}</el-tag>
            </template>
            <template v-if="item.prop == 'slot_ratio'" #default="scope">
              {{ scope.row.slot_ratio }}%
            </template>
          </el-table-column>
        </template>
        <el-table-column fixed="right" label="操作" width="150">
          <template #header>
            <el-tooltip effect="dark" placement="top">
              <template #content>
                模拟登陆：点击可直接登录商户的后台，无需账号密码输入；<br />
                关闭/开启API：控制商户的API接口；关闭后商户玩家无法进入游戏；<br />
                编辑：编辑商户的信息设定及后台账号等；<br />
                删除：删除商户，数据与接口一并删除；此操作无法恢复，谨用；<br />
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            详情
          </template>
          <template #default="scope">
            <div class="flex">
              <el-button :disabled="scope.row.operator_status ? false : true"
                :type="scope.row.status ? 'info' : 'success'" v-permiss="'/system/changeManager'" size="small"
                @click="beforeChange(scope.row)">
                {{ scope.row.status ? '关闭API' : '开启API' }}
              </el-button>
              <el-button type="danger" v-permiss="'/system/destroyManager'" size="small" @click="deleteMerchant(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </template>
    </SearchTable>
  </el-dialog>

  <!-- API批量控制商户 -->
  <el-dialog v-model="data.isShowApi" title="API控制商户" :close-on-click-modal="false" :close-on-press-escape="false"
    top="25vh" @close="onHideDetails(false)">
    <form-item title="API状态" value="status">
      <el-radio-group v-model="data.queryDetails.status" size="large">
        <el-radio-button label="关闭API" :value="0" />
        <el-radio-button label="开启API" :value="1" />
      </el-radio-group>
    </form-item>
    <form-item title="商户类别" v-if="!indexStore.is_general_agent">
      <el-select v-model="data.queryDetails.operated_id" placeholder="请选择" filterable @change="getCommercialList">
        <el-option label="全部" :value="-1" />
        <el-option class="flexBetween" v-for="item in indexStore.operatorArray" :key="item.value"
          :label="'【' + item.value + '】' + item.label" :value="item.value" v-show="item.status">
          【{{ item.value }}】{{ item.label }}
          <el-tag size="small" :type="item.value == 1 ? 'success' : item.type == 1 ? 'danger' : 'warning'"
            style="font-size:10px;">
            {{ item.value == 1 ? '直营' : item.type == 1 ? '多货币' : '正常总代' }}
          </el-tag>
        </el-option>
      </el-select>
    </form-item>
    <form-item title="商户" :pass="true">
      <el-select class="imWidth100" v-model="data.queryDetails.ids" placeholder="请选择" filterable multiple
        @change="chooseAgent">
        <el-option label="全部" :value="-1" />
        <el-option v-for="item in data.commercialArray" :key="item.id" :label="'【' + item.id + '】' + item.agent_name"
          :value="item.id" v-show="item.status == data.queryDetails.status ? false : true && item.operator_status" />
      </el-select>
    </form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="onHideDetails(false)">取 消</el-button>
        <el-button icon="CircleCheck" type="primary" size="small" @click="changApi">确 认</el-button>
      </div>
    </template>         
  </el-dialog>

  <!-- 修改预存分 -->
  <el-dialog v-model="data.isShowScore" title="修改当月预存分" :close-on-click-modal="false" :close-on-press-escape="false"
    top="25vh" @close="onHideDetails(false)">
    <form-item title="当月预存分" :pass="true" value="status">
      <el-input-number class="width200" v-model="data.storeScore" :min="0" :max="9999999999999999" :precision="0"
        placeholder="请输入当月预存分值" clearable controls-position="right" />
    </form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="onHideDetails(false)">取 消</el-button>
        <el-button icon="CircleCheck" type="primary" size="small" @click="scoreMerchant">确 认</el-button>
      </div>
    </template>         
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, h, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import PageDetails from './page-details.vue'
import { exportToExcel } from '@/utils/export'
import { getDateDay, getWeek, setTimeValue, setTimestampTime } from '@/utils/time'
import { throttle, colorClass, selectToLabel, LangConversion, setCommaNumberToArr, sortArray, OperatorServerBrand, AgentCurrency, sortObjectArray } from '@/utils/index'
import { GameBrandNum, APITYPE, DEMOPLAY } from '@/config/eunm'
import { BigDiv, BigHundred, BigTimes, BigWan } from '@/utils/math'
import { COUNTRY } from '@/config/country'
import { getAgent, delAgent, putChangeAgentStatus, editAgentPreScore, editOperatorPreScore ,getAgentApiList, editAgentApi, getAgentSumList } from '@/api/merchant'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    agent_type: -1,
    type: 0,
    app_id: '',
    agent_name: '',
    account: '',
  },
  list: [],
  queryDetails: {
    status: 0,
    operated_id: -1,
    ids: [],
  },
  listDetails: [] as any[],
  commercialArray: [] as any[],
  total: 0,
  conditionList: [
    { label: 'APPID',value: 0 },
    { label: '商户ID',value: 1 }
  ],
  fields: [
    { label: '地区', prop: 'area', width: '120', visible: true, tips: '商户的经营区域，可更改，创建商户时的信息设定' },
    { label: '上级渠道', prop: 'operated_id', width: '210', visible: true, tips: '商户的上级代理名称' },
    { label: '商户ID', prop: 'id', width: '110', visible: true, tips: '商户的ID编号，唯一' },
    { label: 'APP ID', prop: 'app_id', width: '110', visible: true, tips: '商户号，唯一标识；商户接口请求携带参数' },
    { label: '商户秘钥', prop: 'key', width: '150', visible: true, tips: '商户的秘钥' },
    { label: '后台账号', prop: 'account', width: '180', visible: true, tips: '商户的后台登录账号名称' },
    { label: '商户名称', prop: 'agent_name', width: '180', visible: true, tips: '商户名称描述' },
    { label: '当月输赢/预存分值', prop: 'pre_store_score', width: '200', visible: true, tips: '为商户的当月输赢值/为此商户的设定值+上月结余值' },
    { label: '关闭阈值', prop: 'threshold', width: '140', visible: true, tips: '当前的预存分值*（100%+设定值%），若预存分值发生了改变，关闭阈值需实时刷新计算' },
    { label: '商户类型', prop: 'agent_type', width: '145', visible: true, tips: '测试商户：平台与商户对接测试时使用，测试商户的数据不统计，不展示在后台；对接完成后，由测试转为正常；数据正常统计展示' },
    { label: '第三方接口域名', prop: 'domain_name', width: '240', visible: true, tips: '商户的接口地址，平台方用于回调' },
    { label: 'API 状态', prop: 'status', width: '120', visible: true, tips: '显示商户的API接口状态，开启：接口正常请求；关闭：商户无法得到验证，商户玩家无法进入游戏' },
    { label: '结算货币', prop: 'currency_id', width: '150', visible: true, tips: '商户结算货币' },
    { label: 'API接入模式', prop: 'api_type', width: '150', visible: true, tips: '商户接入钱包模式设定' },
    { label: '分成比例', prop: 'config_ggr', width: '200', visible: true, tips: '总代的分成比例' },
    // { label: '商户游戏', prop: 'game', width: '240', visible: true, tips: '商户代理的游戏展示' },
    { label: '创建时间', prop: 'created_at', width: '180', visible: true, tips: '商户的创建生成时间' },
    { label: '最后登录时间', prop: 'last_login_time', width: '180', visible: true, tips: '商户登录后台的最近时间' },
  ],
  dialogVisible: false,
  isShowDetails: false,
  isShowScore: false,
  isShowApi: false,
  formDialogShow: false, // 新增  编辑
  machentShow: false, // 商户类别
  checkedItem: {} as any,
  storeScore: 0,
  totalDate: [
    { label: '今日', value: 1 },
    { label: '昨日', value: 2 },
    { label: '本周', value: 3 },
    { label: '上周', value: 4 },
  ],
  typeList: [
    { label: '全部', value: -1 },
    { label: '正常商户', value: 0 },
    { label: '测试商户', value: 1 },
  ],
  totalForm: {
    total_operator: [],// 总代数量
    agent_num: [],// 商户数量
    access_agent_num: [],// 正在接入的商户数量
    line_agent_num: [],// 已经上线的商户数量
  },
  querySum: {
    type: 1,
    date: [] as any[],
  },
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}

onMounted(async () => {
  // 获取语言
  indexStore.getLanguageList()
  getSearchList()
  data.checkedItem = {} as any
  chooseDate(1)
})

// 查询列表
const getSearchList = async (type?:string) => {
  indexStore.setPageLoading(true)
  let query = JSON.parse(JSON.stringify(data.query))
  if(query.type){
    query.agent_id = Number(query.app_id)
    query.app_id = 0
  }else{
    query.agent_id = Number(query.agent_id)
    query.app_id = Number(query.app_id)
  }
  query = setTimeValue(query)
  if (type && type == 'export') {
    query.size = 10000
  }
  let res = await getAgent(query)
  res.data.list?.forEach((item: any) => {
    item.gameList = sortArray(setCommaNumberToArr(item.game_ids), 'asc')
    item.password = ''
    item.currency = selectToLabel(indexStore.operatorArray, item.operated_id,'currency', 'value')
    // 删除子级商户
    if (data.isShowDetails) {
      if (item.operated_id == data.checkedItem.operated_id && item.son_data) {
        item.son_data?.forEach((second: any) => {
          second.gameList = sortArray(setCommaNumberToArr(second.game_ids), 'asc')
          second.password = ''
        })
        data.listDetails = item.son_data
      }
      if (data.checkedItem.operated_id && !selectToLabel(res.data.list, data.checkedItem.operated_id, 'operated_id', 'operated_id')) {
        data.isShowDetails = false
        data.listDetails = []
      }
    }
    if(item.config_ggr){
      item.config_ggr = sortObjectArray(item.config_ggr,'platform','desc')
    }else{
      item.config_ggr = []
    }
  })
  // 导出
  if (type && type == 'export') {
    getExport(res.data.list)
    return
  }
  data.list = res.data.list
  data.total = res.data.total
}

// 查询列表汇总
const chooseDate = async (type: number) => {
  switch (type) {
    case 1:
      data.querySum.date = [getDateDay(0), getDateDay(0)]
      break;
    case 2:
      data.querySum.date = [getDateDay(-1), getDateDay(-1)]
      break;
    case 3:
      data.querySum.date = getWeek(0)
      break;
    case 4:
      data.querySum.date = getWeek(-1)
      break;
  }
  getSearchSumList()
}
const getSearchSumList = async () => {
  let query = JSON.parse(JSON.stringify(data.querySum))
  query = setTimeValue(query)
  let res = await getAgentSumList(query)
  res.data.access_agent_num = res.data.access_agent_num ? res.data.access_agent_num : []
  res.data.line_agent_num = res.data.line_agent_num ? res.data.line_agent_num : []
  res.data.agent_num = res.data.line_agent_num ? res.data.agent_num : []
  res.data.total_operator = res.data.total_operator ? res.data.total_operator : []
  data.totalForm = res.data
}

// 查看子级商户
const getSunList = (row: any) => {
  if(row.currency!=1){
    return
  }
  if(!row.son_data?.length){
    return ElMessage.error('暂无下一级')
  }
  row.son_data?.forEach((item: any) => {
    item.gameList = sortArray(setCommaNumberToArr(item.game_ids), 'asc')
    item.password = ''
  })
  data.listDetails = row.son_data
  Object.assign(data.checkedItem, row)
  data.isShowDetails = true
}
// 新增/修改
const changeMerchant = (row: any,type:string) => {
  data.checkedItem = row
  if(type=='change'){
    data.formDialogShow = true
  }else{
    data.isShowScore = true
    data.storeScore = row.agent_grade
  }
}
// 删除
const deleteMerchant = async (row: any) => {
  ElMessageBox.confirm('确认删除【' + row.agent_name + '】商户？', '删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    await delAgent({ id: row.id })
    ElMessage.success('操作成功')
    getSearchList()
    indexStore.getAgent() //商户汇总
  }).catch(() => { })
}
// 修改预存分
const scoreMerchant = throttle(async () => {
  let query = JSON.parse(JSON.stringify(data.checkedItem));
  let queryData = { id:query.is_multi_currency ? query.operated_id : query.id, grade:data.storeScore }
  if(!data.storeScore){
    return ElMessage.error('请输入预存分')
  }
  // 多货币商户调用总代接口
  query.is_multi_currency ? await editOperatorPreScore(queryData) : await editAgentPreScore(queryData)
  ElMessage.success('操作成功')
  indexStore.getAgent() //商户汇总
  onHideDetails(false)
  getSearchList()
},5000)

// 商户模拟登录
const agentLogin = async (row: any) => {
  window.open(OperatorServerBrand('sh') + '/login?agent_id=' + row.id + '&token=' + sessionStorage.getItem('PGtoken'), '_blank')
}

// 开关默认
const beforeChange = (row: any) => {
  let msg = row.status? '点击后此商户下的所有游戏进入维护状态,确定将此商户API关闭？':row.pre_score_is_auto_close?'开启此商户的API状态，是否同步开启预存分功能？':'确认激活此商户状态？',dataRow = JSON.parse(JSON.stringify(row));
  dataRow.currency = selectToLabel(indexStore.currentArray, dataRow.currency_id)
  ElMessageBox({
    title: '提示',
    message: h('p', null, [
      h('span', null, msg),
      h('i', { style: 'color: red' }, !row.status && row.pre_score_is_auto_close?'*若要同步开启预存分功能避免再次自动关闭商户，请重新编辑预存分额度':''),
    ]),
    showCancelButton: true,
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    confirmButtonText: !row.status && row.pre_score_is_auto_close?'同步开启':'确定',
    cancelButtonText: !row.status && row.pre_score_is_auto_close?'仅开启API':'取消'
  }).then(async () => {
    dataRow.status = dataRow.status ? 0 : 1
    if(dataRow.pre_score_is_auto_close){
      dataRow.pre_score_status = 1
    }
    await putChangeAgentStatus(dataRow)
    ElMessage.success('操作成功')
    getSearchList()
  }).catch(async() => { 
    if(!row.status && dataRow.pre_score_is_auto_close){
      dataRow.status = dataRow.status ? 0 : 1
      dataRow.pre_score_status = 0
      await putChangeAgentStatus(dataRow)
      ElMessage.success('操作成功')
      getSearchList()
    }
  })
}

// 选择总代-查询总代下所有商户
const getCommercialList = async (id: number) => {
  data.queryDetails.ids = []
  let res = await getAgentApiList({ operated_id: id })
  data.commercialArray = res.data as any
}
// 批量操作API 开关
const changApi = async () => {
  let query = JSON.parse(JSON.stringify(data.queryDetails));
  // 选择全部
  const all = data.queryDetails.ids.find((item: number) => item == -1)
  if (all) {
    query.ids = []
    data.commercialArray.forEach((item: any) => {
      if (item.status != query.status && item.operator_status) {
        query.ids.push(item.id)
      }
    })
  }
  // 商户列表是空的
  if (!query.ids.length && !data.commercialArray.length) {
    return ElMessage.error('暂无有效商户')
  }
  if (!query.ids.length) {
    return ElMessage.error('请选择商户')
  }
  // 上级总代已经关闭
  if (data.queryDetails.operated_id != -1 && !selectToLabel(indexStore.operatorArray, data.queryDetails.operated_id, 'status', 'value')) {
    return ElMessage.error('上级总代已经关闭,请开启之后再次操作！')
  }
  if (query.ids.length == 1 && query.ids[0] == -1) {
    return ElMessage.error(`请勿重复${query.status ? '开启' : '关闭'}商户操作！`)
  }
  await editAgentApi(query);
  ElMessage.success('操作成功')
  onHideDetails(false)
  getSearchList()
}
// 选择商户
const chooseAgent = async (row: any) => {
  const all = row.find((item: number) => item == -1)
  if (all) {
    data.queryDetails.ids = [-1] as any
  } else {
    data.queryDetails.ids = row
  }
}
// 关闭弹框
const cancel = (val?: Boolean) => {
  data.formDialogShow = false
  data.checkedItem = {} as any
  if (val == true) {
    getSearchList()
  }
}

// 导出
const getExport = async (dataList:any) => {
  let header: string[] = []
  let list: never[][] = []

  data.fields.forEach((item) => {
    header.push(item.label)
  })

  dataList.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields.forEach((x) => {
      switch (x.prop) {
        case 'area':
          arr.push(selectToLabel(COUNTRY, item[x.prop]) as never)
          break
        case 'currency_id':
          arr.push(AgentCurrency(item['id']) as never)
          break
        case 'operated_id':
          arr.push(selectToLabel(indexStore.operatorArray, item[x.prop]) as never)
          break
        case 'agent_type':
          arr.push((item[x.prop] ? '测试商户':'正常商户')+(item['kol']?' - KOL':'') as never)
          break
        case 'status':
          arr.push(selectToLabel(DEMOPLAY, item[x.prop]) as never)
          break
        case 'api_type':
          arr.push(selectToLabel(APITYPE, item[x.prop]) as never)
          break
        case 'game':
          let name='';
          if(item['gameList'] && item['gameList'].length){
            item['gameList'].forEach((second:any) => {
              name += selectToLabel(indexStore.gameArray, second)+','
            })
          }
          arr.push(name as never)
          break
        case 'created_at':
          arr.push(setTimestampTime(item[x.prop]) as never)
          break
        case 'last_login_time':
          arr.push(setTimestampTime(item[x.prop]) as never)
          break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '商户列表')
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}
const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}
// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const OperatorRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.isShowDetails = false
  data.isShowApi = false
  data.isShowScore = false
  data.storeScore = 0
  data.queryDetails = {
    status: 0,
    operated_id: -1,
    ids: [],
  }
  if (show) {
    data.query = {
      page: 1,
      size: 50,
      agent_id: -1,
      operated_id: -1,
      agent_type: -1,
      type: 0,
      app_id: '',
      agent_name: '',
      account: '',
    }
    OperatorRef.value.onHideDetails()
    getSearchList()
  }
}
</script>

<style scoped lang="scss">
.ratio {
  display: flex;
  justify-content: space-between;

  span {
    color: crimson;
  }
}
.flexWrap {
  max-width: 240px;
  max-height: 300px;
  overflow: auto;
}
</style>